
//
//  SaoMaViewController.m
//  fff
//
//  Created by 张利强 on 2016/11/10.
//  Copyright © 2016年 hbyj. All rights reserved.
//

#import "SaoMaViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SaoMiaoJieGuoViewController.h"


#import "PQHistoryBarCodeTableViewController.h"
#define WH WIDTH*0.15
#define SaomiaoWH WIDTH*0.7
#define sacle 4/414
#define saomiaoH SaomiaoWH*28/464
//#define DefaultColor [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]
#define BarCodeHistory [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"history.plist"]


@interface SaoMaViewController ()<AVCaptureMetadataOutputObjectsDelegate,CCResultViewControllerDelegate>
{
    CFURLRef        soundFileURLRef;
    
    SystemSoundID   soundFileObject;
}
@property (readwrite)   CFURLRef        soundFileURLRef;

@property (readonly)    SystemSoundID   soundFileObject;

@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, strong) UIView *maskingview;

@property (nonatomic, strong) UIImageView *animation;

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

/**bool*/
@property (nonatomic, assign) BOOL isStart;

@property (nonatomic, strong) NSTimer *timer;

/**开关灯按钮*/
@property (nonatomic, strong) UIButton *buttonLight;

/**装载扫描记录的数组*/
@property (nonatomic, strong) NSMutableArray *BarCodeArray;

@end

@implementation SaoMaViewController

@synthesize soundFileURLRef,soundFileObject,buttonLight;

- (NSMutableArray *)BarCodeArray{
    if (_BarCodeArray.count == 0) {
        NSArray *array = [NSArray arrayWithContentsOfFile:BarCodeHistory];
        if (array) {
            _BarCodeArray = [NSMutableArray arrayWithContentsOfFile:BarCodeHistory];
        }else{
            _BarCodeArray = [NSMutableArray array];
        }
    }
    return _BarCodeArray;
}

- (void)viewWillAppear:(BOOL)animated{
    
    //[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //[self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    self.tabBarController.tabBar.hidden = YES;
    //[[JTNavigationController alloc]init].fullScreenPopGestureEnabled = NO;
    
    UIButton *buttonRight = [[UIButton alloc]init];
    buttonRight.cc_width = 24;
    buttonRight.cc_height = 24*46/50;
    [buttonRight setImage:[UIImage imageNamed:@"history"] forState:normal];
    [buttonRight addTarget:self action:@selector(buttonRightTap:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:buttonRight];
    
    [_session startRunning];
}

#pragma mark - 代理方法
- (void)removeAllobjects{
    [self.BarCodeArray removeAllObjects];
}

-(void)buttonRightTap:(UIButton *)btn{
    PQHistoryBarCodeTableViewController *history = [[PQHistoryBarCodeTableViewController alloc]initWithStyle:UITableViewStylePlain];
    history.delegate = self;
    history.BarCodeArray = self.BarCodeArray;
    [self.navigationController pushViewController:history animated:YES];
}

- (void)appHasGoneInForeground:(NSNotificationCenter *)center{
    
    [self startAni];
    [self.session startRunning];
}

- (void)appHasGoneInBackground:(NSNotificationCenter *)center{
    
    [self.animation removeFromSuperview];
    [self.session stopRunning];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /**在页面加载完毕时添加通知*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appHasGoneInForeground:) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appHasGoneInBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    /**初始化页面元素*/
    [self initUI];
    /**设置页面名称*/
    self.navigationItem.title = @"二维码/条形码";
    /**设置title的颜色*/
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    /**设置导航栏按钮颜色*/
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    
}

/**在初始化摄像头时，如果不支持摄像头或者没有授权时，弹出对话框，提示用户*/
- (void)showWithStatus:(NSString *)string{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionCancle = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:actionCancle];
    [self presentViewController:alert animated:YES completion:nil];
}

/*
- (void)initUI{
    
    // 1. 实例化拍摄设备
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2. 设置输入设备
    
    NSError *error;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    // 3. 设置元数据输出
    NSString *mediaType = AVMediaTypeVideo;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        [self addMasking];
        NSString *string = @"请在iPhone的“设置”-“隐私”-“相机”功能中，找到“品桥购”打开相机访问权限";
        [self showWithStatus:string];
        return;
    }
    if (error) {
        [self addMasking];
        NSString *string = @"抱歉！你手机不支持二维码扫描!";
        [self showWithStatus:string];
        return;
    }
    
    // 3.1 实例化拍摄元数据输出
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    // 3.3 设置输出数据代理
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 4. 添加拍摄会话
    
    // 4.1 实例化拍摄会话
    
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    
    // 设置高质量的值
    
    if ([UIScreen mainScreen].bounds.size.height == 480)
        
    {
        
        [session setSessionPreset:AVCaptureSessionPreset640x480];
        
    }
    
    else
        
    {
        
        [session setSessionPreset:AVCaptureSessionPresetHigh];
        
    }
    
    // 4.2 添加会话输入
    
    if ([session canAddInput:input])
    {
        [session addInput:input];
    }
    
    // 4.3 添加会话输出
    
    if ([session canAddOutput:output])
    {
        [session addOutput:output];
    }
    
    // 4.3 设置输出数据类型，需要将元数据输出添加到会话后，才能指定元数据类型，否则会报错
    
    output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
                                   
                                   AVMetadataObjectTypeEAN8Code,
                                   
                                   AVMetadataObjectTypeCode128Code,
                                   
                                   AVMetadataObjectTypeQRCode];
    
    //设置扫描信息的识别区域，左上角为(0,0),右下角为(1,1),不设的话全屏都可以识别。设置过之后可以缩小信息扫描面积加快识别速度。
    //这个属性并不好设置，整了半天也没太搞明白，到底x,y,width,height,怎么是对应的，这是我一点一点试的扫描区域，看不到只能调一下，扫一扫试试
    [output setRectOfInterest: CGRectMake (( 64+WH )/ HEIGHT ,WH/ WIDTH , SaomiaoWH / HEIGHT , SaomiaoWH / WIDTH )];
    
    self.session = session;
    
    // 5. 视频预览图层
    
    // 5.1 实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
    
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    
    preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    preview.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    
    // 5.2 将图层插入当前视图
    
    [self.view.layer insertSublayer:preview atIndex:1];
    
    self.previewLayer = preview;
    
    [self addMasking];
    
    // 6. 启动会话
    
    [_session startRunning];

}
*/

- (void)initUI{
    
    // 1. 实例化拍摄设备
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2. 设置输入设备
    
    NSError *error;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    // 3. 设置元数据输出
    NSString *mediaType = AVMediaTypeVideo;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        [self addMasking];
        NSString *string = @"请在iPhone的“设置”-“隐私”-“相机”功能中，找到“品桥购”打开相机访问权限";
        [self showWithStatus:string];
        return;
    }
    if (error) {
        [self addMasking];
        NSString *string = @"抱歉！你手机不支持二维码扫描!";
        [self showWithStatus:string];
        return;
    }
    
    // 3.1 实例化拍摄元数据输出
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    // 3.3 设置输出数据代理
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 4. 添加拍摄会话
    
    // 4.1 实例化拍摄会话
    
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    
    // 设置高质量的值
    
    if ([UIScreen mainScreen].bounds.size.height == 480)
        
    {
        
        [session setSessionPreset:AVCaptureSessionPreset640x480];
        
    }
    
    else
        
    {
        
        [session setSessionPreset:AVCaptureSessionPresetHigh];
        
    }
    
    // 4.2 添加会话输入
    
    if ([session canAddInput:input])
    {
        [session addInput:input];
    }
    
    // 4.3 添加会话输出
    
    if ([session canAddOutput:output])
    {
        [session addOutput:output];
    }
    
    // 4.3 设置输出数据类型，需要将元数据输出添加到会话后，才能指定元数据类型，否则会报错
    
    output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
                                   
                                   AVMetadataObjectTypeEAN8Code,
                                   
                                   AVMetadataObjectTypeCode128Code,
                                   
                                   AVMetadataObjectTypeQRCode];
    
    //设置扫描信息的识别区域，左上角为(0,0),右下角为(1,1),不设的话全屏都可以识别。设置过之后可以缩小信息扫描面积加快识别速度。
    //这个属性并不好设置，整了半天也没太搞明白，到底x,y,width,height,怎么是对应的，这是我一点一点试的扫描区域，看不到只能调一下，扫一扫试试
    [output setRectOfInterest: CGRectMake (( 64+WH )/ HEIGHT ,WH/ WIDTH , SaomiaoWH / HEIGHT , SaomiaoWH / WIDTH )];
    
    self.session = session;
    
    // 5. 视频预览图层
    
    // 5.1 实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
    
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    
    preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    preview.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    
    // 5.2 将图层插入当前视图
    
    [self.view.layer insertSublayer:preview atIndex:1];
    
    self.previewLayer = preview;
    
    [self addMasking];
    
    // 6. 启动会话
    
    [_session startRunning];
}


- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    // 3. 设置界面显示扫描结果
    
    if (metadataObjects.count > 0)
        
    {
        // 1. 如果扫描完成，停止会话
        
        [self.session stopRunning];
        
        [self.animation removeFromSuperview];
        
        NSString *string = [[NSBundle mainBundle] pathForResource:@"VoiceSearchOn.wav" ofType:@""];
        //把音频文件转换成url格式
        NSURL *url = [NSURL fileURLWithPath:string];
        //初始化音频类 并且添加播放文件
        self.soundFileURLRef = (__bridge CFURLRef)(url);
        
        AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
        
        AudioServicesPlaySystemSound (soundFileObject);
        
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        
        NSDate *currentDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm"];
        NSString *dateString = [dateFormatter stringFromDate:currentDate];
        
        NSDictionary *dic = @{@"type":obj.type,@"string":obj.stringValue,@"time":dateString};
        
        [self.BarCodeArray addObject:dic];
        
        [self.BarCodeArray writeToFile:BarCodeHistory atomically:YES];
        
        // 判断获取到的是不是字符串 还是 网址
        NSRange range = NSMakeRange(0, 4);
        NSString *str = [obj.stringValue substringWithRange:range];
        
        if ([str isEqualToString:@"http"]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"可能存在风险，是否打开此链接？" message:obj.stringValue preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *Cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self startAni];
                [self.session startRunning];
            }];
            UIAlertAction *Ok = [UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 4.跳转控制器
                SaoMiaoJieGuoViewController *result = [[SaoMiaoJieGuoViewController alloc]init];
                result.valueForPage = obj.stringValue;
                
                //NSLog(@"~~~~~~~~%@",obj.stringValue);
                
                result.isURL = YES;
                result.delegate = self;
                [self.navigationController pushViewController:result animated:YES];
            }];
            [alert addAction:Cancle];[alert addAction:Ok];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else{
            // 4.跳转控制器
            SaoMiaoJieGuoViewController *result = [[SaoMiaoJieGuoViewController alloc]init];
            result.valueForPage = obj.stringValue;
            result.isURL = NO;
            result.delegate = self;
            [self.navigationController pushViewController:result animated:YES];
        }
    }
}


- (void)addMasking{
    
    _maskingview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64+WH)];
    topView.backgroundColor = DefaultColor;
    [_maskingview.layer insertSublayer:topView.layer atIndex:200];
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 64+WH, WH, HEIGHT- 64 - WH)];
    leftView.backgroundColor = DefaultColor;
    [_maskingview.layer insertSublayer:leftView.layer atIndex:200];
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(WIDTH *0.85, 64+WH, WH, HEIGHT- 64 - WH)];
    rightView.backgroundColor = DefaultColor;
    [_maskingview.layer insertSublayer:rightView.layer atIndex:200];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(WH, 64+WH+SaomiaoWH, SaomiaoWH, HEIGHT- 64 - WH - SaomiaoWH)];
    bottomView.backgroundColor = DefaultColor;
    [_maskingview.layer insertSublayer:bottomView.layer atIndex:200];
    
    UIImageView *topImageview = [[UIImageView alloc]initWithFrame:CGRectMake(WH-WIDTH*sacle, 64+WH-WIDTH*sacle, SaomiaoWH+WIDTH*sacle*2, saomiaoH)];
    topImageview.image = [UIImage imageWithContentsOfFile:image(@"newbarcode_scan_box_top")];
    [_maskingview.layer insertSublayer:topImageview.layer atIndex:201];
    
    UIImageView *bottomImageview = [[UIImageView alloc]initWithFrame:CGRectMake(WH-WIDTH*sacle, 64+WH+SaomiaoWH-saomiaoH+WIDTH*sacle, SaomiaoWH+WIDTH*sacle*2, saomiaoH)];
    bottomImageview.image = [UIImage imageWithContentsOfFile:image(@"newbarcode_scan_box_bottom")];
    [_maskingview.layer insertSublayer:bottomImageview.layer atIndex:201];
    
    UIImageView *centerImageview = [[UIImageView alloc]initWithFrame:CGRectMake(WH-WIDTH*sacle, 64+WH-WIDTH*sacle+saomiaoH, SaomiaoWH+WIDTH*sacle*2, SaomiaoWH - (saomiaoH - WIDTH*sacle)*2)];
    centerImageview.image = [UIImage imageWithContentsOfFile:image(@"newbarcode_scan_box_mid")];
    [_maskingview.layer insertSublayer:centerImageview.layer atIndex:201];
    
    [self startAni];
    
    [self.view.layer insertSublayer:_maskingview.layer atIndex:150];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 64+WH-30, WIDTH, 30)];
    label.text = @"对准二维码/条形码到框内即可扫描";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:12];
    label.textAlignment = NSTextAlignmentCenter;
    [_maskingview addSubview:label];
    
    UIView *viewbuttonback = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    viewbuttonback.cc_centerX = WIDTH/2;
    viewbuttonback.cc_y = 114 + WH + SaomiaoWH;
    viewbuttonback.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    viewbuttonback.layer.masksToBounds = YES;
    viewbuttonback.layer.cornerRadius = 20;
    [self.view insertSubview:viewbuttonback atIndex:300];
    
    buttonLight = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
//    [buttonLight setImage:[UIImage imageWithContentsOfFile:image(@"newbarcode_light_off")] forState:normal];
//    [buttonLight setImage:[UIImage imageWithContentsOfFile:image(@"newbarcode_light_on")] forState:UIControlStateSelected];
    
    [buttonLight setImage:[UIImage imageNamed:@"newbarcode_light_off"] forState:normal];
    [buttonLight setImage:[UIImage imageNamed:@"newbarcode_light_on"] forState:UIControlStateSelected];
    
    [buttonLight addTarget:self action:@selector(buttonLightTap:) forControlEvents:UIControlEventTouchUpInside];
    [viewbuttonback addSubview:buttonLight];
}

- (void)buttonLightTap:(UIButton *)button{
    buttonLight.selected = !button.selected;
    if (buttonLight.selected) {
        [self turnTorchOn:YES]; //打开闪光灯
    }else{
        [self turnTorchOn:NO]; //关闭闪光灯
    }
}

//调用系统闪光灯
- (void)turnTorchOn:(BOOL)on {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){
            
            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

- (void)removeMaskingview{
    [self.maskingview removeFromSuperview];
}

- (void)startAni{
    
    _animation = [[UIImageView alloc] initWithFrame:CGRectMake(WH, 64+WH, SaomiaoWH, 0)];
//    _animation.image = [UIImage imageWithContentsOfFile:image(@"qrcode_scan_full_net")];
    _animation.image = Image(@"qrcode_scan_full_net");
    [_maskingview.layer insertSublayer:_animation.layer atIndex:1];
    
    
    
    [UIView animateWithDuration:2 delay:0.01 options:UIViewAnimationOptionRepeat animations:^{
        _animation.cc_height = SaomiaoWH;
    } completion:^(BOOL finished) {
        _animation.cc_height = 0;
    }];
}

@end
